package org.jfk.core;

import org.apache.log4j.Logger;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;

public class MyInterceptor implements Interceptor {
	private static Logger logger = Logger.getLogger(MyInterceptor.class);

	@Override
	public void intercept(Invocation ai) {
		logger.debug("MyInterceptor start...");
//		logger.debug("getActionKey = "+ai.getActionKey());
//		logger.debug("getControllerKey = "+ai.getControllerKey());
//		logger.debug("getMethodName = "+ai.getMethodName());
//		logger.debug("getViewPath = "+ai.getViewPath());
		try {
//			User user = (User)ai.getController().getSession().getAttribute("currUser");
//			if (user == null){
//				ai.getController().setAttr("errMsg","user login invalid");
//				throw new RuntimeException("user login invalid");
//			}
			
			
			ai.invoke();
		} catch (RuntimeException e) {
			ai.getController().setAttr("errMsg", getExceptionDetail(e));
			throw e;
		}
		logger.debug("MyInterceptor end...");
	}

	/**
	 * 获取exception详情信息
	 * 
	 * @param e
	 *            Excetipn type
	 * @return String type
	 */
	public static String getExceptionDetail(Throwable e) {
		StringBuffer msg = new StringBuffer("");
		if (e == null) {
			return null;
		}
		while (e.getCause() != null) {
			e = e.getCause();
		}

		String message = e.toString();

		int length = e.getStackTrace().length;

		if (length > 0) {

			msg.append(message + "\n");

			for (int i = 0; i < length; i++) {

				msg.append("\t" + e.getStackTrace()[i] + "\n");

			}
		} else {
			msg.append(message);
		}
		return msg.toString();

	}


}
